<?php
namespace app\service;
use EasyWeChat\Factory;
use app\service\LogService;
use app\service\OrderService;
use app\common\model\Order as OrderModel;
use app\common\model\ChatMoney as ChatMoneyModel;
use app\common\model\User as UserModel;
use app\common\model\ChatMsg as ChatMsgModel;
use app\common\model\Loginstatus;
use app\common\model\VideoPay as VideoPayModel;


use EasyWeChat\Kernel\Messages\NewsItem;


class PayService extends BaseService
{
  public static $payment;
  public function __construct()
  {
    $config = [
      //'app_id' => config('authorizer_appid'),
      'app_id' => config('wechat_appid'),
      'mch_id' => config('wechat_mchid'),
      'key' => config('wechat_mchkey'),
      //'notify_url'         => request()->domain()."/notify/wechat/mall_id/".$this->mall_id, 
      'cert_path' => config('wechat_mchcertpem'),
      'key_path'  => config('wechat_mchkeypem'),
    ];
    self::$payment =  Factory::payment($config);
  }


  /* 微信支付退款 */
  public function wechatRefund ($orderInfo,$refund_no=false) {
    if(!$refund_no) {
      $refund_no = $orderInfo['order_sn'].time();
    }
    $money = (int)($orderInfo['pay_money']*100);
    $result = self::$payment->refund->byOutTradeNumber($orderInfo['order_sn'], $refund_no, $money,$money, [
        'refund_desc' => '用户订单退款',
    ]);
    //dump($money);die;
    LogService::S()->writeLog("data",'wechatRefund',$result);
    if($result['return_code']=='SUCCESS' && $result['return_msg']=='OK') {
      return true;
    }
    return json_encode($result);
  }


  /* 企业付款 */
  public function qiyePay ($log,$userInfo) {
    $result = self::$payment->transfer->toBalance([
      'partner_trade_no' => 'qiyepay'.$log['id'], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
      //'openid' => UserModel::uid2openid($log['uid']),
      'openid' => $userInfo['openid_main'],
      'check_name' => 'FORCE_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
      're_user_name' => $log['bank_card_name'], // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
      'amount' => $log['atm_money']*100, // 企业付款金额，单位为分
      'desc' => '社群资金提现', // 企业付款操作说明信息。必填
    ]);
    if($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS') {
      return true;
    }
    return $result['err_code_des'];
  }

  /* 获取支付sdk */
  public function wechatJssdk ($config) {
    $config['total_fee'] = (int)$config['total_fee'];
    $result = self::$payment->order->unify($config);
    $jsapi = self::$payment->jssdk->sdkConfig($result['prepay_id']);
    return $jsapi;
  }

  /* 微信发红包支付成功 */
  public function wechatMoneySuccess () {
   
      $response = self::$payment->handlePaidNotify(function ($message, $fail) {
     // LogService::S()->writeLog('WechatPayLog','',$message);
      $moneyLog = ChatMoneyModel::getOne([
        'order_sn' => $message['out_trade_no']
      ]);
      if(!$moneyLog || $moneyLog['status']!=0) {
        return true;
      }
      $userInfo = UserModel::getOneById($moneyLog['uid']);
      if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
        if ($message['result_code'] === 'SUCCESS') {
          ChatMoneyModel::where('id',$moneyLog['id'])->update(
            ['status' => 1]
          );
          //红包消息
          ChatMsgModel::create([
            'uid' => $moneyLog['uid'],
            'other' => $moneyLog['id'],
            'content' => json_encode([
                'type' => 'message',
                'uid' => $moneyLog['uid'],
                'content' => [
                  'content' => $moneyLog['desc'],
                  'id' => $moneyLog['id'],
                  'type' => 'money',
                  'money' => $moneyLog['money'],
                  'nickname' => $userInfo['nickname'],
                  'uid' => $moneyLog['uid'],
                  'status' => true
                ]
            ]),
            'status' => 0,
            'type' => 'money',
            'mall_id' => $userInfo['mall_id'],
            'group_id' => UserModel::getGroupId($moneyLog['uid'])
          ]); 
      
          $obj = WechatService::S([
            'mall_id' => $userInfo['mall_id']
          ]);
           $recentList = Loginstatus::getAll([
              'update_time' => [
                  'egt',time()-3600*24
              ],
              'mall_id' => $userInfo['mall_id']
          ],"",'uid');
          // LogService::S()->writeLog('$recentList','st',$recentList);
          //$recentList = UserModel::getRencentList($moneyLog['uid']);
          //LogService::S()->writeLog("st",'ts',$recentList);
          if($recentList) {
              foreach($recentList as $v) {
                  $re=$obj->send(
                      2,
                      UserModel::uid2openid($v['uid']),
                      [new NewsItem([
                        'title'       => $userInfo['nickname']."在群内发了一个红包,快来抢红包吧",
                        'description' => '',
                        'url'         => request()->domain()."/m/chat/pages/index/index?rid=".$moneyLog['id']."&mall_id={$userInfo['mall_id']}",
                        'image'       => "http://cdn.1s1s.club/shopcom/20190510/1725488242.png",
                      ])]
                  );
                  LogService::S()->writeLog('result','code1',$re);
              }
          }

        } else {
            LogService::S()->writeLog('$fail','filed','通信失败,请稍后再通知我');
            return $fail('通信失败，请稍后再通知我');
        }
      } else {
          return $fail('通信失败，请稍后再通知我');
      }
      // 或者错误消息
    });
    return $response->send();
  }

  /* 支付成功回调 */
  public function wechatPaySuccess () {
    $response = self::$payment->handlePaidNotify(function ($message, $fail) {
      LogService::S()->writeLog('WechatPayLog','',$message);
      $order = OrderModel::getOne([
        'order_sn' => $message['out_trade_no']
      ]);
      if(!$order || $order['checked']!=0) {
        return true;
      }
      if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
        if ($message['result_code'] === 'SUCCESS') {
          OrderService::S()->changeOrder($order,[
            'checked' => 1,
            'pay_time' => time(),
          ]);
        } else {
            return $fail('通信失败，请稍后再通知我');
        }
      } else {
          return $fail('通信失败，请稍后再通知我');
      }
      // 或者错误消息
    });
    return $response->send();
  }

  public function wechatVideoSuccess () {
    $response = self::$payment->handlePaidNotify(function ($message, $fail) {
      LogService::S()->writeLog('WechatPayLog','',$message);
      $order = VideoPayModel::getOne([
        'order_sn' => $message['out_trade_no']
      ]);
      if(!$order || $order['status']!=0) {
        return true;
      }
      if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
        if ($message['result_code'] === 'SUCCESS') {
          VideoPayModel::where([
            'id' => $order['id']
          ])->update([
            'status' => 1
          ]);
        } else {
            return $fail('通信失败，请稍后再通知我');
        }
      } else {
          return $fail('通信失败，请稍后再通知我');
      }
      // 或者错误消息
    });
    return $response->send();
  }

}